//
//  YHYAddViewController.m
//  Home
//
//  Created by 杨泓晔 on 16/4/27.<yhy编辑>
//  Copyright © 2016年 LanJue. All rights reserved.
//

#import "YHYAddViewController.h"
#import "YHYDesignerPTableViewCell.h"
#import "WSShopInfoNextView.h"
#import "DCPaymentView.h"
#import "WSCustomPickerView.h"
#import "AppDelegate.h"
#import "YHYSelectViewController.h"
#import "TZTestCell.h"
//#import "YHYSeaPictureViewController.h"
#import "TZImagePickerController.h"
//#import "UIView+Five.h"
#import "UIView+Layout.h"
#import "YHYDesignRequireTableViewCell.h"
#import "YHYStyleTableViewCell.h"
#import "YHYButtonTableViewCell.h"
#import "SeaPictureViewController.h"
#import "YHYPictureCollectionViewCell.h"
#import "YHYAddmyMainModel.h"
#import "YHYDetailTableViewCell.h"
#define angelToRandian(x)  ((x)/180.0*M_PI)
@interface YHYAddViewController ()<UITableViewDataSource,UITableViewDelegate,WSCustomPickerViewDelegate,UITableViewDelegate,UITableViewDataSource,YHYSelectViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,TZImagePickerControllerDelegate,YHYButtonTableViewdelegate,YHYDesignRequireDelegate,YHYStyleDelegate>{
    NSInteger index;
    CGFloat _itemWH;
    CGFloat _margin;
    CGFloat _fH;
    
    
    NSMutableArray *_selectedAssets;
    
    NSInteger a;
    NSIndexPath *indexP;
    UITableView *commentText;
    UITapGestureRecognizer *recognizer;
}
@property (nonatomic,strong)UITableView *myTableView;
@property (nonatomic,strong)NSArray *array;
@property (nonatomic,strong)NSArray *arrTwo;
@property (nonatomic,strong)NSString *name;
@property (nonatomic,strong)WSCustomPickerView *customPicker;
@property (nonatomic,strong)NSString *styleL;
@property (nonatomic,strong)NSString *addressL;
@property (nonatomic,strong)NSString *sizeL;
@property (nonatomic,strong)NSString *xiL;
@property (nonatomic,strong)NSString *styleRequire;
@property (nonatomic,strong)NSString *yearL;
@property (nonatomic,strong)NSString *priceL;

@property (nonatomic,strong)YHYSelectViewController *yhy;
//@property (nonatomic,retain)TZTestCell *cell;

@property (nonatomic,strong)AppDelegate *myAppDelegate;
@property (nonatomic,strong)UIView *myBackBigView;
//@property (nonatomic,strong)NSMutableArray *mycollectionVArray;


@property (nonatomic,assign)NSInteger selectArray;
@property (nonatomic,strong)UICollectionViewFlowLayout *layout;
@property (nonatomic,strong)UICollectionView *myCollectionView;
@property (nonatomic,strong)UILabel *numLabel;
@property (nonatomic,strong)UIButton *button;


@property (nonatomic,retain)NSIndexPath *myindexPath;
@property (nonatomic,retain)NSMutableArray *seaArr;
@property (nonatomic,retain)UILabel *textnameL;
@property (nonatomic,retain)NSIndexPath *tapIndexPath;

@property (nonatomic,retain) YHYAddmyMainModel *myModel;

@property (nonatomic,retain)NSString *picName;
/**
 *  传设计要求点击的内容
 */
@property (nonatomic,retain)NSString *designStr;

@property (nonatomic,retain) NSData *data;
@property (nonatomic,assign)NSInteger numOfContent;
@property (nonatomic, retain)NSString *textStr;//输入内容



@end

@implementation YHYAddViewController

- (void)viewWillAppear:(BOOL)animated {
    
    //    self.navigationController.navigationBarHidden = NO;
    self.title = @"发布任务";
    self.tabBarController.tabBar.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"arr" object:nil];
    self.tabBarController.tabBar.hidden=YES;
    
    self.navigationController.navigationBar.translucent = YES;
    
    [self.myCollectionView reloadData];
}

-(void) viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden=NO;
}

- (void)viewDidLoad {
    [self creatView];
    
    self.selectedPhotos = [NSMutableArray array];
    
    
    
//    if (_selectedPhotos != nil) {
//        
//        for (NSMutableDictionary *dic in _myEditModel.imgs) {
//            NSString *url_image = [NSString stringWithFormat:@"%@%@",HTTPURL,[dic objectForKey:@"simg"]];
//            NSString *id = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
//            UIImageView *imageV = [UIImageView new];
//            [imageV sd_setImageWithURL:[NSURL URLWithString:url_image]];
//            NSURL *url = [NSURL URLWithString:url_image];
//            imageV.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
//            
//            NSMutableDictionary *dica = [NSMutableDictionary dictionary];
//            [dica setObject:imageV.image forKey:@"img"];
//            [dica setObject:id forKey:@"id"];
//            [_selectedPhotos addObject:dica];
//            
//        }
//        [self changeUICollectionView];
//    }
//
    if (_myEditModel != nil) {
        _selectedPhotos  = [NSMutableArray arrayWithArray:_myEditModel.imgs];
    }

    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(Back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    _margin = 4 * AUTO_HEIGHT;
    _itemWH = (self.view.tz_width - 20 * AUTO_WIDTH-2 * _margin - 7) / 3 - _margin;
    self.layout.itemSize = CGSizeMake(_itemWH, _itemWH  - 1 );
    self.layout.minimumInteritemSpacing = _margin;
    self.layout.minimumLineSpacing = 10  * AUTO_HEIGHT ;
    _myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0 * AUTO_WIDTH, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (150 * AUTO_HEIGHT* (0))) collectionViewLayout:self.layout];
    
    
    
    _selectedAssets = [NSMutableArray array];
    self.myindexPath = [NSIndexPath new];
    _seaArr = [NSMutableArray array];
    self.numLabel = [UILabel new];
    self.tapIndexPath = [NSIndexPath new];
    _myCollectionView.backgroundColor = [UIColor whiteColor];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)
                                                 name:@"UITextViewTextDidChangeNotification" object:commentText];
    NSLog(@"CCCCCCCCCCC%@",_myEditModel.title);
    [_myTableView reloadData];
  }


- (void)creatView{
    self.array = [NSArray arrayWithObjects:@"任务名称", @"任务类型",@"任务地址",@"任务面积（㎡）",nil];
    
    _arrTwo = [NSArray arrayWithObjects:@"设计经验",@"项目总价（元）", nil ];
    
    
    self.myTableView = [UITableView new];
    
    [self.view addSubview:self.myTableView];
    self.myTableView.rowHeight = 50 * AUTO_HEIGHT;
    
    // self.myTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view);
        make.left.mas_equalTo(self.view);
        make.height.mas_equalTo(self.view.frame.size.height + 50 * AUTO_HEIGHT);
        make.width.mas_equalTo(self.view);
        
    }];
    //_myTableView.scrollEnabled = NO;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.backgroundColor = LV;
    [self.myTableView registerClass:[YHYDesignerPTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableView registerClass:[YHYDesignerPTableViewCell class] forCellReuseIdentifier:@"cell123"];
    
    [self.myTableView registerClass:[YHYDesignRequireTableViewCell class] forCellReuseIdentifier:@"YHYDesignRequireTableViewCell"];
    [self.myTableView registerClass:[YHYStyleTableViewCell class] forCellReuseIdentifier:@"YHYStyleTableViewCell"];
    [self.myTableView registerClass:[YHYButtonTableViewCell class] forCellReuseIdentifier:@"YHYButtonTableViewCell"];
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ce"];
    [self.myTableView registerClass:[YHYDetailTableViewCell class] forCellReuseIdentifier:@"YHYDetailTableViewCell"];
    [[UITableViewHeaderFooterView appearance] setTintColor:LV];
    //    _myCollectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (150 * AUTO_HEIGHT* (a)));
    
    [_myCollectionView reloadData];
    [_myTableView reloadData];
    
    
}

- (void)presentStr:(NSString *)pic{
    _picName = pic;
}

- (void)postUrl{
    NSString *url = [NSString stringWithFormat:@"%@%@",JIAFANURL,@"Gafaer/Task/CreateTask"];
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    NSString *code = [LOCALSEVE objectForKey:@"MCODE"];
    NSString *uid = [LOCALSEVE objectForKey:@"UID"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 20 ;
    
    
    if (_myEditModel != nil) {
        
        NSMutableDictionary *dic =[NSMutableDictionary dictionary];
        [dic setObject:uid forKey:@"uid"];
        [dic setObject:code forKey:@"mcode"];
        [dic setObject:_name forKey:@"title"];//任务名称
        [dic setObject:_styleL forKey:@"tasktype"];//任务类型
        [dic setObject:_picName forKey:@"style"];//风格要求
        [dic setObject:_sizeL forKey:@"mianji"];//任务面积
        [dic setObject:_designStr forKey:@"sjyq"];//设计要求，多选
        [dic setObject:_yearL forKey:@"exper"];//设计经验
        [dic setObject:_priceL forKey:@"money"];//价格
        [dic setObject:_textStr forKey:@"detail"];//详细描述
        //
        //
        NSArray *addressArray = [self.addressL componentsSeparatedByString:@" "];
        [dic setObject:addressArray[0] forKey:@"province"];
        [dic setObject:addressArray[1] forKey:@"city"];
        [dic setObject:addressArray[2] forKey:@"area"];
        [dic setObject:[NSString stringWithFormat:@"%ld",_myEditModel.id] forKey:@"id"];
        
        
        
        
        
        [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            for ( NSInteger i = 0; i < _selectedPhotos.count; i ++) {
                for (NSMutableDictionary *dic in _selectedPhotos) {
                    NSString *id = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
                    int i;
                    if ([dic objectForKey:id] != nil) {
                        
                        [_selectedPhotos removeObject:dic];
                    }
                    i++;
                    
                }
                NSData *imageData = UIImageJPEGRepresentation(_selectedPhotos[i], 0.2);
                NSString *Name = [NSString stringWithFormat:@"img%ld",i];
                NSString *fileName = [NSString stringWithFormat:@"%@.jpg",Name];
                [formData appendPartWithFileData:imageData name:Name fileName:fileName mimeType:@"image/jpeg" ];
            }
            
            
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *responseData;
            NSError *error = nil;
            if (responseObject != nil) {
                responseData = [NSJSONSerialization JSONObjectWithData:responseObject
                                                               options:NSJSONReadingMutableContainers
                                                                 error:&error];
                
                NSLog(@"jjjjjjj=%@",responseData);
                NSLog(@"success");
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error%@",error);
            
        }];
        
    }
    
    
    
    else{
        
        NSMutableDictionary *dic =[NSMutableDictionary dictionary];
        
        [dic setObject:uid forKey:@"uid"];
        [dic setObject:code forKey:@"mcode"];
        [dic setObject:_name forKey:@"title"];//任务名称
        [dic setObject:_styleL forKey:@"tasktype"];//任务类型
        [dic setObject:_picName forKey:@"style"];//风格要求
        [dic setObject:_sizeL forKey:@"mianji"];//任务面积
        [dic setObject:_designStr forKey:@"sjyq"];//设计要求，多选
        [dic setObject:_yearL forKey:@"exper"];//设计经验
        [dic setObject:_priceL forKey:@"money"];//价格
        [dic setObject:_textStr forKey:@"detail"];//详细描述
        
        
        NSArray *addressArray = [self.addressL componentsSeparatedByString:@" "];
        [dic setObject:addressArray[0] forKey:@"province"];
        [dic setObject:addressArray[1] forKey:@"city"];
        [dic setObject:addressArray[2] forKey:@"area"];
        [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            for ( NSInteger i = 0; i < _selectedPhotos.count; i ++) {
                NSData *imageData = UIImageJPEGRepresentation(_selectedPhotos[i], 0.2);
                NSString *Name = [NSString stringWithFormat:@"img%ld",i];
                NSString *fileName = [NSString stringWithFormat:@"%@.jpg",Name];
                [formData appendPartWithFileData:imageData name:Name fileName:fileName mimeType:@"image/jpeg" ];
            }
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *responseData;
            NSError *error = nil;
            if (responseObject != nil) {
                responseData = [NSJSONSerialization JSONObjectWithData:responseObject
                                                               options:NSJSONReadingMutableContainers
                                                                 error:&error];
                
                
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error%@",error);
            
        }];
        
    }
    
}





//






- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 7;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 0) {
        
        return 8 * AUTO_HEIGHT;
    }
    
    if (section == 1) {
        
        return 8 * AUTO_HEIGHT;
    }
    if (section == 2) {
        return 8 * AUTO_HEIGHT;
    }
    if (section == 3) {
        return 8 * AUTO_HEIGHT;
    }
    if (section == 4) {
        return 8 * AUTO_HEIGHT;
    }
    
    return 0;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return _array.count;
    }
    if (section == 1) {
        return 1;
    }
    if (section == 2) {
        return 1;
    }
    if (section == 3) {
        return _arrTwo.count;
    }
    if (section == 4) {
        return 1;
    }
    if (section == 5) {
        return 1;
    }
    if (section == 6) {
        return 1;
    }
    
    return 0;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *str = @"cell123";
    YHYDesignerPTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:str];
    
    cell2.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section ==0) {
        cell2.xmLabel.text = _array[indexPath.row];
        if (indexPath.row == 0) {
            if (_name == nil) {
                cell2.WXlabel.text = _myEditModel.title;
                _name = _myEditModel.title;
            }
            else {
                
                cell2.WXlabel.text = _name;
                
                
            }
            
            
            
        }
        //任务类型
        if (indexPath.row == 1) {
            if (_styleL == nil) {
                index = 3;
                cell2.WXlabel.text = _myEditModel.tasktype;
                _styleL = _myEditModel.tasktype;
            }
            else{
                cell2.WXlabel.text = _styleL;
            }
        }
        
        
        
        //地址
        if (indexPath.row == 2) {
            if (_addressL == nil) {
                if (_myEditModel != nil) {
                    NSString *provinceStr = _myEditModel.province;
                    NSString *cityStr = _myEditModel.city;
                    NSString *areaStr = _myEditModel.area;
                    NSString *str = [NSString stringWithFormat:@"%@ %@ %@",provinceStr,cityStr,areaStr];
                    cell2.WXlabel.text =str;
                    _addressL = str;
                }
                
            }
            else{
                cell2.WXlabel.text = _addressL;
            }
        }
        //面积
        if (indexPath.row == 3) {
            if (_sizeL == nil) {
                if (_myEditModel != nil) {
                    
                    cell2.WXlabel.text = [NSString stringWithFormat:@"%ld",_myEditModel.mianji];
                    _sizeL = [NSString stringWithFormat:@"%ld",_myEditModel.mianji];
                }
            }
            else{
                cell2.WXlabel.text = _sizeL;
            }
        }
        
    }
    
    
    if  (indexPath.section == 1){
        
        if (indexPath.row == 0) {
            YHYDesignRequireTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHYDesignRequireTableViewCell"];
            if (_myEditModel != nil) {
                cell.dicStr = _myEditModel.sjyq;
                _designStr = _myEditModel.sjyq;
            }
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.mydeleagte = self;
            return cell;
            
        }
        
    }
    //风格要求
    if (indexPath.section == 2) {
        YHYStyleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHYStyleTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.myDelegate = self;
        
        if (_myEditModel != nil) {
            cell.picttureModelStr = _myEditModel.style;
            _picName = _myEditModel.style;
            
        }
        else{
            _picName = cell.pictureName;
        }
        return cell;
    }
    
    if (indexPath.section == 3) {
        static NSString *str = @"cell";
        YHYDesignerPTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        cell.xmLabel.text = _arrTwo[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            if (_yearL == nil) {
                
                
                cell.WXlabel.text = _myEditModel.exper;
                _yearL = _myEditModel.exper;
            }
            else{
                cell.WXlabel.text = _yearL;
            }
            
        }
        if (indexPath.row == 1) {
            if (_priceL ==nil) {
                if (_myEditModel != nil) {
                    
                    cell.WXlabel.text = [NSString stringWithFormat:@"%ld",_myEditModel.money];
                    _priceL = _myEditModel.exper;
                }
            }
            else{
                cell.WXlabel.text = _priceL;
            }
            
        }
        
        return cell;
        
    }
    
    //图片
    if (indexPath.section == 4) {
        UITableViewCell *cell3 = [tableView dequeueReusableCellWithIdentifier:@"ce" forIndexPath:indexPath];
        
        
        
        cell3.selectionStyle = UITableViewCellSelectionStyleNone;
        cell3.backgroundColor = LV;
        indexP = indexPath;
        
        
        
        
        //    裁掉view的边界
        self.myCollectionView.layer.masksToBounds = NO;
        //    设置半径
        //self.myCollectionView.layer.cornerRadius = 6 * AUTO_WIDTH;
        self.myCollectionView.scrollEnabled = NO;
        // self.myCollectionView.backgroundColor = [UIColor whiteColor];
        [self changeUICollectionView];
        [cell3 addSubview:_myCollectionView];
        
        
        _myCollectionView.contentInset = UIEdgeInsetsMake(13 * AUTO_WIDTH, 15 * AUTO_HEIGHT, 5 * AUTO_WIDTH, 15 * AUTO_HEIGHT);
        _myCollectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -2 * AUTO_HEIGHT);
        _myCollectionView.dataSource = self;
        _myCollectionView.delegate = self;
        
        
        [self changeUICollectionView];
        [_myCollectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
        [_myCollectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTest"];
        [_myCollectionView registerClass:[YHYPictureCollectionViewCell class] forCellWithReuseIdentifier:@"YHYPicCollectionViewCell"];
        UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonLongPressed:)];
        [_myCollectionView addGestureRecognizer:longGesture];
        
        
        
        [cell3 addSubview:self.numLabel];
        self.numLabel.textColor = [UIColor blackColor];
        self.numLabel.alpha = 0.6;
        self.numLabel.font = [UIFont systemFontOfSize:TEXTLABELFONT*TEXTWEIGHT];
        [self changeUICollectionView];
        
        [self.numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_myCollectionView.mas_bottom).offset(2 * AUTO_HEIGHT);
            make.left.mas_equalTo(cell3.mas_right).offset( - 50  * AUTO_WIDTH);
            make.height.mas_equalTo(15 * AUTO_WIDTH);
            
            
        }];
        
        self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
        
        [_myCollectionView reloadData];
        
        return cell3;
        
        
        
        
        self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
        
        
        
        
    }
    if (indexPath.section == 5) {
        YHYDetailTableViewCell *detailCell = [tableView dequeueReusableCellWithIdentifier:@"YHYDetailTableViewCell"];
        detailCell.myTextView.delegate = self;
        
        
        
        if (_textStr ==nil) {
            //                if (_myEditModel != nil) {
            
            detailCell.myTextView.text = _myEditModel.detail;
            _textStr = _myEditModel.detail;
            //                }
        }
        
        
        
        
        
        
        
        
        return  detailCell;
    }
    
    
    if (indexPath.section == 6) {
        
        
        YHYButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHYButtonTableViewCell"];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
    
    return cell2;
    
}


- (void)goNext:(UIButton *)btu{
    
    [self.navigationController popViewControllerAnimated:YES];
}
//UICollectionView长按响应
- (void)buttonLongPressed:(UILongPressGestureRecognizer *)longPress
{  [self changeUICollectionView];
    
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
        {
            
            NSIndexPath *selectedIndex = [[NSIndexPath alloc] init];
            CGPoint point = [longPress locationInView:_myCollectionView];
            selectedIndex = [_myCollectionView indexPathForItemAtPoint:point];
            [_myCollectionView beginInteractiveMovementForItemAtIndexPath:selectedIndex];
            TZTestCell *mycell = (TZTestCell *)[_myCollectionView cellForItemAtIndexPath:selectedIndex];
            if (selectedIndex.row == _selectedPhotos.count) {
                //左后一个不抖动
            }
            else{
                [self shakeAnimationForView:mycell.imageView point:point];
            }
            
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [_myCollectionView updateInteractiveMovementTargetPosition:[longPress locationInView:_myCollectionView]];
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            // 啥意思打上注释:就是当他移动时，到边距ok，移动到一定位置就删除
            [_myCollectionView endInteractiveMovement];
            NSIndexPath *selectedIndex = [[NSIndexPath alloc] init];
            CGPoint point = [longPress locationInView:_myCollectionView];
            
            selectedIndex = [_myCollectionView indexPathForItemAtPoint:point];
            
            if (point.x < 50 || point.y < 50 || point.x > _itemWH * 3  - 30 || point.y > _itemWH * 3  - 40) {
                //          是图片
                [_selectedPhotos removeObjectAtIndex:_myindexPath.item];
                
                //                _myCollectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (100 * AUTO_HEIGHT* (a)));
                [self changeUICollectionView];
                
                
                NSLog(@"asasasas%@",_selectedPhotos);
                NSLog(@"zzzzzzz%ld",(unsigned long)_selectedPhotos.count);
                self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
                
                
                
                
                
                //
                TZTestCell *mycell = (TZTestCell *)[_myCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:_selectedPhotos.count inSection:0]];
                mycell.imageView.image = [UIImage imageNamed:@"jia"];
                [_myTableView reloadData];
                [_myCollectionView reloadData];
                
            }
            
            
        }
            
            break;
        default:
            [_myCollectionView cancelInteractiveMovement];
            break;
    }
    
    
    
    
}





//通知响应方法
- (void)change:(NSNotification *)notification
{
    NSMutableArray *ar = [notification object];
    self.selectedPhotos = ar;
    NSLog(@"qqqq%@",ar);
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    [_myCollectionView reloadData];
    
}

#pragma mark - 发布协议
- (void)presentDelegate{
    [self postUrl];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 设计要求
- (void)presentDic:(NSMutableDictionary *)dic button:(NSInteger)btu{
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < dic.allKeys.count; i++) {
        NSString *str = [dic objectForKey:dic.allKeys[i]];
        [array insertObject:str atIndex:i];
        
    }
    _designStr = [array componentsJoinedByString:@","];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSLog(@"number:%ld", _selectedPhotos.count);
    if (_selectedPhotos.count >= 9) {
        if (_myEditModel.imgs != nil) {
            return _myEditModel.imgs.count + _selectedPhotos.count;
        }
        else{
        return _selectedPhotos.count + 1;
        }
    }
    else{
        return _selectedPhotos.count + 1;
        
    }
    
    
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    
    
    if (indexPath.row == _selectedPhotos.count && _selectedPhotos.count <= 9) {
        
        TZTestCell *cell1 =  [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTest" forIndexPath:indexPath];
        cell1.imageView.image = [UIImage imageNamed:@"jia"];
        
        return cell1;
    }
    else{
        TZTestCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];

        
        
        if (_myEditModel.imgs != nil) {
            cell.imageView.backgroundColor = [UIColor purpleColor];
            NSMutableArray *picArray = [NSMutableArray array];
            for (NSMutableDictionary *dic in _myEditModel.imgs) {
                NSString *url_image = [NSString stringWithFormat:@"%@%@",HTTPURL,[dic objectForKey:@"simg"]];
                NSString *id = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
                UIImageView *imageV = [UIImageView new];
                [imageV sd_setImageWithURL:[NSURL URLWithString:url_image]];
                NSURL *url = [NSURL URLWithString:url_image];
                imageV.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
             
                [picArray addObject:imageV.image];
            }
            
            cell.imageView.image = picArray[indexPath.row];
            
//            if (picArray.count- 1  ==  indexPath.item) {
//                
//            
//            cell.imageView.image = _selectedPhotos[indexPath.item + 1];
//            }
            return cell;
            
            
        }
        
        

        
        
        return cell;
    }
    
        
        
        
    
    
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _selectedPhotos.count) {
        
        
        [self pickPhotoButtonClick:nil];
        
    }
    else{
        
        SeaPictureViewController *yhySeaVC = [SeaPictureViewController new];
        yhySeaVC.seaArray  = [NSMutableArray arrayWithArray:_selectedPhotos];
        yhySeaVC.indexNumber = (NSInteger)indexPath.item;
        
        NSLog(@"sssssss%ld",yhySeaVC.indexNumber);
        [self.navigationController pushViewController:yhySeaVC animated:YES];
        
        
        
        
    }
    
    
}
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    _myindexPath = indexPath;
    if ([collectionView numberOfItemsInSection:indexPath.section] <= 1) {
        return NO;
    }
    if (indexPath.row == _selectedPhotos.count) {
        return NO;
    }
    
    return YES;
}


- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    
    
    _tapIndexPath = sourceIndexPath;
    
    
    if (destinationIndexPath.row != _selectedPhotos.count) {
        
        
        NSString *selectObject = _selectedPhotos[sourceIndexPath.item];
        self.myindexPath = sourceIndexPath;
        //从资源数组中移除该数据
        [_selectedPhotos removeObject:selectObject];
        
        
        
        
        
        
        NSMutableArray *destinationArr = _selectedPhotos;
        [destinationArr insertObject:selectObject atIndex:destinationIndexPath.row];
        _selectedPhotos = [NSMutableArray arrayWithArray:destinationArr];
        
    }else{
#pragma mark -后改动的
        
        
    }
    
    
    [self changeUICollectionView];
    [_myCollectionView reloadData];
    [_myTableView reloadData];
    
    
}


#pragma mark Click Event

- (IBAction)pickPhotoButtonClick:(UIButton *)sender {
    //    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:5 delegate:self];
    NSInteger mum = 9;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc]initWithMaxImagesCount:mum selectArr:_selectedPhotos delegate:self];
    imagePickerVc.selectCount = _selectedPhotos.count;
    //    NSLog(@"asas%ld",(long)imagePickerVc.selectCount);
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
    [self changeUICollectionView];
    [_myCollectionView reloadData];
    [_myTableView reloadData];
    
}


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    [_selectedPhotos addObjectsFromArray:photos];
    //  NSLog(@"wwww%ld",(unsigned long)photos.count);
    //[self configCollectionView];
    
    
    
    _myCollectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
    
    
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    [self changeUICollectionView];
    [_myTableView reloadData];
    [_myCollectionView reloadData];
    
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return CGSizeMake(_itemWH, _itemWH);
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 2.0 * AUTO_WIDTH, 0);
}






- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            DCPaymentView *payAlert = [[DCPaymentView alloc] init];
            payAlert.title = [NSString stringWithFormat:@"任务名称"];
            // [payAlert setTextFieldKeyBordToNum];
            payAlert.numOfContent = 5;
            [payAlert show];
            payAlert.completeHandle = ^(NSString *inputPwd) {
                
                self.name = [NSString stringWithFormat:@"%@", inputPwd];
                
                [_myTableView reloadData];
            };
            
        }
        
        if (indexPath.row == 1) {
            index = 3;
            self.customPicker = nil;
            self.customPicker = [[WSCustomPickerView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) dataArr:[NSArray arrayWithObjects:@"室内设计",@"工装设计",@"软装设计",@"3D设计",@"建筑设计",@"园林设计", nil]];
            self.customPicker.delegate = self;
            self.customPicker.titleStr = @"任务类型";
            [self.view addSubview:_customPicker];
            [self.customPicker showPicker];
            
        }
        
        
        if (indexPath.row == 2) {
            index = 2;
            self.customPicker = nil;
            self.customPicker = [[WSCustomPickerView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
            self.customPicker.delegate = self;
            self.customPicker.titleStr = @"任务地址";
            [self.view addSubview:_customPicker];
            [self.customPicker showPicker];
        }
        //        if (indexPath.row ==3) {
        //            NSLog(@"详细地址");
        //        }
        
        if (indexPath.row == 3) {
            DCPaymentView *payAlert = [[DCPaymentView alloc] init];
            payAlert.title = [NSString stringWithFormat:@"任务面积"];
            [payAlert setTextFieldKeyBordToNum];
            payAlert.numOfContent = 5;
            [payAlert show];
            payAlert.completeHandle = ^(NSString *inputPwd) {
                
                _sizeL = [NSString stringWithFormat:@"%@", inputPwd];
                
                [_myTableView reloadData];
                
            };
            
        }
        
        
    }
    
    
#pragma mark - 自己需要
    
    
    if (indexPath.section == 3) {
        if (indexPath.row == 0) {
            
            index = 5;
            self.customPicker = nil;
            self.customPicker = [[WSCustomPickerView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) dataArr:[NSArray arrayWithObjects:@"应届生",@"1年以内",@"1-3年",@"3-5年",@"5-10年",@"10年以上", nil]];
            self.customPicker.delegate = self;
            self.customPicker.titleStr = @"设计经验";
            [self.view addSubview:_customPicker];
            [self.customPicker showPicker];
            
            
        }
    }
    if (indexPath.row == 1 && indexPath.section==3) {
        NSLog(@"元");
        index = 6;
        DCPaymentView *payAlert = [[DCPaymentView alloc] init];
        payAlert.title = [NSString stringWithFormat:@"项目总价"];
        [payAlert setTextFieldKeyBordToNum];
        payAlert.numOfContent = 4;
        [payAlert show];
        payAlert.completeHandle = ^(NSString *inputPwd) {
            
            self.priceL = [NSString stringWithFormat:@"%@元", inputPwd];
            
            [_myTableView reloadData];
            
        };
        
    }
    
}

//协议
- (void)presentDiemess:(NSInteger)arraynum{
    _selectArray = arraynum;
    [_yhy removeFromSuperview];
    [_myBackBigView removeFromSuperview];
    [_myTableView reloadData];
}
//任务类型 单滑动
- (void)sendAddressInfo:(NSString *)address{
    if (index == 1) {
        
    }
    if (index == 2) {
        
        _addressL = address;
        
    }
    if (index == 3) {
        
        if (_styleL == nil) {
            //            cell2.WXlabel.text = _myEditModel.tasktype;
            _styleL=address;
        }
        else{
            //            cell2.WXlabel.text = _styleL;
            _styleL= _myEditModel.tasktype;
            
        }
        
        
        
        
        
    }
    if (index == 4) {//风格要求
        _styleRequire = address;
    }
    if (index == 5) {
        _yearL = address;
    }
    
    [_myTableView reloadData];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        //  if (indexPath.row == 0) {
        return 80 * AUTO_HEIGHT;
        //  }
        
    }
    if (indexPath.section == 2) {
        return 310 * AUTO_HEIGHT;
    }
    if (indexPath.section == 4) {
        
        
        //        NSInteger b = _selectedPhotos.count;
        if (_selectedPhotos.count < 3 ) {
            a = 0;
            
        }
        if (_selectedPhotos.count >= 3 && _selectedPhotos.count <= 5) {
            
            a = 1;
        }
        if ( _selectedPhotos.count > 5 && _selectedPhotos.count <= 9) {
            a = 2;
        }
        return 170 * AUTO_HEIGHT  + (150 * AUTO_HEIGHT* (a)- 40 * (a));
    }
    [self changeUICollectionView];
    [_myCollectionView reloadData];
    
    
    // return 470 * AUTO_HEIGHT;
    
    if (indexPath.section == 5) {
        return 140 * AUTO_HEIGHT;
    }
    
    if (indexPath.section == 6) {
        return 140 * AUTO_HEIGHT;
    }
    return ROWHEIGHT;
}


- (void)changeUICollectionView{
    
    if (_selectedPhotos.count < 3 ) {
        a = 0;
        
    }
    if (_selectedPhotos.count >= 3 && _selectedPhotos.count <= 5) {
        
        a = 1;
    }
    if ( _selectedPhotos.count > 5 && _selectedPhotos.count <= 9) {
        a = 2;
    }
    
    
    _myCollectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (110 * AUTO_HEIGHT* (a))- 0 * AUTO_HEIGHT * (a));
    
    
}


- (void)shakeAnimationForView:(UIView *)view point:(CGPoint)point{
    //获取到当前的View
    CALayer *viewLayer = view.layer;
    //获取当前View位置
    CGPoint position = viewLayer.position;
    //    CGPoint x = CGPointMake(position.x + 0, position.y + 20);
    //    CGPoint y = CGPointMake(position.x - 0, position.y - 20);
    
    //    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    //    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    //    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    //    [animation setToValue:[NSValue valueWithCGPoint:y]];
    //    [animation setAutoreverses:YES];
    //    [animation setDuration:0.06];
    //    [animation setRepeatCount:3];
    //    [viewLayer addAnimation:animation forKey:nil];
    //
    
    CAKeyframeAnimation* anim=[CAKeyframeAnimation animation];
    anim.keyPath=@"transform.rotation";
    anim.values=@[@(angelToRandian(-7)),@(angelToRandian(7)),@(angelToRandian(-7))];
    anim.repeatCount=MAXFLOAT;
    anim.duration=0.2;
    anim.repeatCount = 3;
    [view.layer addAnimation:anim forKey:nil];
    
}



-(void)textFiledEditChanged:(NSNotification *)obj
{
    UITextView *textField = (UITextView *)obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [textField.textInputMode primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
    {
        //获取高亮部分
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (toBeString.length > 199)
            {
                textField.text = [toBeString substringToIndex:199];
            }
        }
        
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else
    {
        if (toBeString.length > 199)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:_numOfContent];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:199];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 199)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}
//开始触发键盘
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView

{
    recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapAction:)];
    [self.view addGestureRecognizer:recognizer];
    
    
    //    if (_selectedPhotos.count != 0) {
    //        [UIView animateWithDuration:.7f delay:0.f usingSpringWithDamping:.7f initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    //        } completion:nil];
    
    [UIView animateWithDuration:.3f animations:^{
        self.view.frame = CGRectMake(0, - 190 * AUTO_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
        
    }];
    
    //   }
    
    
    
    //   [self.view removeGestureRecognizer:recognizer];
    
    
    
    
    return YES;
}


-(void)textViewDidChange:(UITextView *)textView
{
    
    //    self.textV.text = textView.text;
    //    if (textView.text.length == 0) {
    //        self.uilabel.text = @"一句话介绍自己，和大家打声招呼，写写现在的心情";
    //    }else{
    //        self.uilabel.text = @"";
    //    }
    
    //    self.intA =[self characterCountOfString:self.textV.text];
    //    self.numChiese = [self chineseCountOfString:self.textV.text];
    //    self.numLabel.text = [NSString stringWithFormat:@"%ld/40",(self.numChiese + self.intA)];
    
    
    NSLog(@"dawe");
    
}
- (void)TapAction:(UITapGestureRecognizer *)tap{
    
    [self.view endEditing:YES];
    //  NSLog(@"hhhhhh=%@",commentText.text);
    
    UITapGestureRecognizer *longPress = (UITapGestureRecognizer *)tap;
    UIGestureRecognizerState state = longPress.state;
    
    CGPoint location = [longPress locationInView:self.myTableView];
    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:location];
    NSLog(@"%@",indexPath);
    
    
    
    
    [UIView animateWithDuration:0.20f animations:^{
        
        
        self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        
    }];
    
    
    [commentText resignFirstResponder];
    [self.view removeGestureRecognizer:recognizer];
}



-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        
        [UIView animateWithDuration:0.20f animations:^{
            
            
            self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            
        }];
        
        NSString *temp = [textView.text stringByReplacingCharactersInRange:range
                                                                withString:text];
        
        // _textStr = temp;
        
        NSLog(@"uuuu=%@",temp);
        _textStr = temp;
        
        [self heightForContent:temp];
        [_myTableView reloadData];
        return NO;
        
    }
    
    return YES;
    
    
}
//文字是配

- (CGFloat)heightForContent:(NSString *)content
{
    //参数1.设置计算高度按照什么样的size来计算
    //注意: 宽度一定与Label宽度一致，高度尽量大一点
    CGSize size = CGSizeMake(300, 10000);
    //参数2.设置计算类型
    //参数3.设置计算内容按照多大字体计算
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:20.0], NSFontAttributeName, nil];
    //注意: 字体大小也要跟Label字体一样
    //参数4.系统备用参数，设置为nil
    CGRect frame = [content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    _fH = frame.size.height;
    [_myTableView reloadData];
    return frame.size.height;
}



- (void)Back:(UIButton*)btu{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
